﻿using CozeDomain.Entities;
using CozeDomain.IRepositories;
using CozeDto.ConsumptionHistoryDtos;
using D.UtilFreesqlOrm;

namespace CozeDomain.Repositories
{
    public class ConsumptionHistoryEntityRepository : BaseRepository<ConsumptionHistoryEntity>, IConsumptionHistoryEntityRepository
    {
        public ConsumptionHistoryEntityRepository(IFreeSql db) : base(db)
        {
        }

        public async Task<Tuple<long, List<RepConsumptionHistoryInfo>>> QueryConsumptionHistoryPagesAsync(ReqQueryConsumptionHistoryPage reqQueryConsumptionHistoryPage)
        {

            var where = _db.Select<ConsumptionHistoryEntity, UserEntity>()
                                                               .LeftJoin((a, b) => a.UserId == b.Id)
                                                               .Where((a, b) => a.TenantId == reqQueryConsumptionHistoryPage.TenantId)
                                                               .WhereIf(!string.IsNullOrEmpty(reqQueryConsumptionHistoryPage.UserId), (a, b) => a.UserId == reqQueryConsumptionHistoryPage.UserId)
                                                               .WhereIf(!string.IsNullOrEmpty(reqQueryConsumptionHistoryPage.Account), (a, b) => b.Account.Contains(reqQueryConsumptionHistoryPage.Account));

            var dbres = await where.Count(out var totalCount)
                                                            .Page(reqQueryConsumptionHistoryPage.PageNo, reqQueryConsumptionHistoryPage.PageSize)
                                                            .ToListAsync((a, b) => new RepConsumptionHistoryInfo()
                                                            {
                                                                Account = b.Account,
                                                                Amount = a.Amount,
                                                                CreateTime = a.CreateTime,
                                                                CreateUser = a.CreateUser,
                                                                Description = a.Description,
                                                                Id = a.Id,
                                                                UpdateTime = a.UpdateTime,
                                                                UpdateUser = a.UpdateUser
                                                            });

            return new Tuple<long, List<RepConsumptionHistoryInfo>>(totalCount, dbres);
        }
    }
}
